import 'dart:async';

import 'package:flutter/material.dart';
import 'package:shopping_group/base/base_constant.dart';
import 'package:shopping_group/base/page_constance.dart';
import 'package:shopping_group/entity/task_entity.dart';
import 'package:shopping_group/event/event.dart';
import 'package:shopping_group/http/apis/apis.dart';
import 'package:shopping_group/modle/person/bloc/my_money_bloc.dart';
import 'package:shopping_group/modle/main/entity/commo_spec4app_record_entity.dart';
import 'package:shopping_group/modle/play/bloc/fugou_runing_play_bloc.dart';
import 'package:shopping_group/modle/play/entity/user_account_entity.dart';
import 'package:shopping_group/res/colors.dart';
import 'package:shopping_group/res/dimens.dart';
import 'package:shopping_group/utils/object_util.dart';
import 'package:shopping_group/utils/route_util.dart';
import 'package:shopping_group/utils/widget_utils.dart';
import 'package:shopping_group/view/button_progress_view.dart';
import 'package:bot_toast/bot_toast.dart';
import 'dart:js' as js;

class FuGouRuningPalyPage extends StatefulWidget {
  final CommoSpec4AppRecordEntity entity;
  FuGouRuningPalyPage({Key key, this.entity}) : super(key: key);

  @override
  _FuGouRuningPalyPageState createState() => _FuGouRuningPalyPageState();
}

class _FuGouRuningPalyPageState extends State<FuGouRuningPalyPage> {
//时间格式
  //String _content = '00:59:59';
  FugouRuningPlayBloc _bloc;
  MyMoneyBloc _myMoneyBloc;
  List<TaskEntity> _selectList = [];
  UserAccountEntity _entity = UserAccountEntity();
  StreamSubscription _zfbStartListSubscription;
  StreamSubscription _zfbCallblackListSubscription;
  StreamSubscription _zfbCompleteListSubscription;
  StreamSubscription _wxStartListSubscription;
  @override
  void initState() {
    super.initState();
    _bloc = FugouRuningPlayBloc();
    // _bloc.timerDate.add(_content);
    _myMoneyBloc = MyMoneyBloc();
    _myMoneyBloc.initDate.add(null);

    // bool notye = BaseConstant.PO_ZI_FU_BAO ==
    //         this.widget.entity.valEntity.payCase.selPayOption
    //     ? true
    //     : false;
    // bool isZfbUse =
    //     this.widget.entity.valEntity.payCase.zfbPayAll.canUseing == 'Y'
    //         ? true
    //         : false;
    // bool isNbUse =
    //     this.widget.entity.valEntity.payCase.innerAcctPayFirst.canUseing == 'Y'
    //         ? true
    //         : false;
    _selectList
      // ..add(TaskEntity()
      //   ..id = '1'
      //   ..title = '支付宝全额支付'
      //   ..url = 'http://static.jiujiupingou.com/Static/img/bg23.png'
      //   ..imageName = 'icon_pay_alipay'
      //   ..isCilke = !isZfbUse ? false : notye
      //   ..isUse = isZfbUse)
      ..add(TaskEntity()
        ..id = '2'
        ..title = '微信支付'
        ..url = 'http://static.jiujiupingou.com/Static/img/bg21.png'
        ..imageName = 'icon_pay_wechat'
        ..isCilke = true
        ..isUse = true);

    _zfbCompleteListSubscription =
        eventBus.on<ZfbCompeteEvent>().listen((event) {
      BotToast.closeAllLoading();
      String openType = this.widget.entity.openType;
      String orderId = this.widget.entity.orderId;
      if (openType == 'order') {
        eventBus.fire(RefreshOrderEvent(orderId));
        RouteUtil.closeView();
      } else if ('fuGood' == openType) {
        RouteUtil.popUntil(PageConstance.MAIN_PAGE);
        RouteUtil.goView(PageConstance.ALL_ORDER_PAGE);
      } else if ('dfk' == openType) {
        RouteUtil.popUntil(PageConstance.MAIN_PAGE);
        RouteUtil.goView(PageConstance.DFK_VIEW_PAGE);
      } else {
        RouteUtil.popUntil(PageConstance.MAIN_PAGE);
        RouteUtil.goView(PageConstance.ALL_ORDER_PAGE);
      }
    });

    _zfbCallblackListSubscription =
        eventBus.on<ZfbCallbackEvent>().listen((event) {
      Map<String, dynamic> data = {};
      data['val'] = event.id;
      _bloc.zfbPlayCompeteDate.add(data);
    });

    _zfbStartListSubscription = eventBus.on<ZfbStartEvent>().listen((event) {
      Map<String, dynamic> data = event.parm.toJson();
      data['type'] = BaseConstant.SHOP_TYPE;
      data['orderName'] = this.widget.entity.name;
      data['appOrWeb'] = 'WEB';
      // data['payType'] = 'PT_ZFB';
      _bloc.zfbPlayDate.add(data);
    });

    _wxStartListSubscription = eventBus.on<WxStartEvent>().listen((event) {
      if (null != event && event.url is String) {
        String ecurl = Uri.encodeComponent(
            '${Apis.WEB_URL}?type=redirectUrl&orderId=${event.orderId}&orderName=${event.orderName}&openType=${event.openType}');
        String reUrl = 'redirect_url=$ecurl';

        StringBuffer url = StringBuffer();
        List<String> gdLists = event.url.split('&');
        int count = gdLists.length;
        for (var i = 0; i < count; i++) {
          if (count - 1 != i) {
            url..write(gdLists[i])..write('&');
          } else {
            url..write(reUrl);
          }
        }
        flutterRsetUrl(url.toString());
      }
    });
  }

  void flutterRsetUrl(url) {
    js.context.callMethod("flutterRsetUrl", [url]);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: WidgetUtils.showAppar(context, '去支付'),
      body: Container(
        height: double.infinity,
        decoration: new BoxDecoration(
          color: Colours.gray_f0,
        ),
        child: Stack(
          children: <Widget>[
            SingleChildScrollView(
              scrollDirection: Axis.vertical,
              reverse: false,
              padding: EdgeInsets.all(0.0),
              physics: BouncingScrollPhysics(),
              child: Column(
                children: <Widget>[
                  //_timeView(),
                  // SizedBox(
                  //   height: 32,
                  // ),
                  _moneyView(),
                  SizedBox(
                    height: 8,
                  ),
                  _selectView(),
                  SizedBox(
                    height: 48,
                  ),
                ],
              ),
            ),
            Positioned(
              bottom: 0,
              right: 0,
              left: 0,
              top: MediaQuery.of(context).size.height / 2 +
                  MediaQuery.of(context).size.height / 3 -
                  32,
              child: ButtonProgressView.crateCupertinoView('确认支付',
                  blackColor: Colours.main_01, cupertinoCall: () {
                _selectList.forEach((element) {
                  if (element.isCilke && '1' == element.id) {
                    _zfBloc(element);
                    return;
                  } else if (element.isCilke && '2' == element.id) {
                    _weichat(element);
                    return;
                  }
                });
              }),
            ),
            SizedBox(
              height: 32,
            ),
          ],
        ),
      ),
    );
  }

  _weichat(element) {
    Map<String, dynamic> data = {};

    data['userId'] = BaseConstant.userId;
    data['shopOrderId'] = this.widget.entity.orderId;
    data['commoSpecId'] = this.widget.entity.id;
    data['shopCt'] = this.widget.entity.count;
    data['getGoodInfoId'] = BaseConstant.adressEntity.id;
    data['payVal'] = this.widget.entity.valEntity.payCase.shopPrice;
    data['payOption'] = BaseConstant.PO_ZI_FU_BAO;
    data['openType'] = this.widget.entity.openType;
    data['orderId'] = this.widget.entity.orderId;
    data['payType'] = "PT_WX";
    data['custGroupsRelaId'] = this.widget.entity.custGroupsRelaId;
    data['payCase'] = this.widget.entity.valEntity.payCase;
    data['price'] = this.widget.entity.valEntity.payCase.selPayOption ==
            BaseConstant.PO_ZI_FU_BAO
        ? this.widget.entity.valEntity.payCase.shopPrice
        : this
            .widget
            .entity
            .valEntity
            .payCase
            .innerAcctPayFirst
            .zfbAcct
            .mustPay;
    data['isUserZfb'] = 'N';
    _bloc.playDate.add(data);
  }

  _zfBloc(element) {
    Map<String, dynamic> data = {};

    data['userId'] = BaseConstant.userId;
    data['shopOrderId'] = this.widget.entity.orderId;
    data['commoSpecId'] = this.widget.entity.id;
    data['shopCt'] = this.widget.entity.count;
    data['getGoodInfoId'] = BaseConstant.adressEntity.id;
    data['payVal'] = this.widget.entity.valEntity.payCase.shopPrice;
    data['payOption'] = this.widget.entity.valEntity.payCase.selPayOption =
        (element.isCilke && '2' == element.id)
            ? BaseConstant.PO_INNER
            : BaseConstant.PO_ZI_FU_BAO;
    data['openType'] = this.widget.entity.openType;
    data['orderId'] = this.widget.entity.orderId;
    data['custGroupsRelaId'] = this.widget.entity.custGroupsRelaId;
    data['payCase'] = this.widget.entity.valEntity.payCase;

    String isUserZfb = (this.widget.entity.valEntity.payCase.selPayOption ==
                    BaseConstant.PO_INNER &&
                !ObjectUtil.isEmptyString(this
                    .widget
                    .entity
                    .valEntity
                    .payCase
                    .innerAcctPayFirst
                    .zfbAcct
                    .mustPay) &&
                double.parse(this
                        .widget
                        .entity
                        .valEntity
                        .payCase
                        .innerAcctPayFirst
                        .zfbAcct
                        .mustPay) >
                    0) ||
            this.widget.entity.valEntity.payCase.selPayOption ==
                BaseConstant.PO_ZI_FU_BAO
        ? 'Y'
        : 'N';
    data['isUserZfb'] = isUserZfb;
    data['price'] = this.widget.entity.valEntity.payCase.selPayOption ==
            BaseConstant.PO_ZI_FU_BAO
        ? this.widget.entity.valEntity.payCase.shopPrice
        : this
            .widget
            .entity
            .valEntity
            .payCase
            .innerAcctPayFirst
            .zfbAcct
            .mustPay;
    _bloc.playDate.add(data);
  }

  Widget _selectView() {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 8),
      alignment: Alignment.centerLeft,
      decoration: BoxDecoration(
        color: Colours.title_white,
      ),
      child: Column(
        children: <Widget>[
          WidgetUtils.getTextColorView(
              '选择支付方式', Colours.text_2222, Dimens.FONT_SIZE_18),
          SizedBox(
            height: 16,
          ),
          _selectFsView(),
        ],
      ),
    );
  }

  Widget _selectFsView() {
    return StreamBuilder(
      stream: _myMoneyBloc.sendAllData,
      initialData: _entity,
      builder: (BuildContext contexts, AsyncSnapshot<Object> snapshot) {
        Object object = snapshot.data;
        if (object is UserAccountEntity) {
          _entity = object;
        }
        return Column(
          children: _selectList.map((TaskEntity entity) {
            //   bool isEnd = _selectList[_selectList.length - 1].id == entity.id;
            return GestureDetector(
              onTap: () {
                setState(() {
                  if (entity.isUse) {
                    _selectList.forEach((element) {
                      element.isCilke = false;
                    });
                    entity.isCilke = true;
                  }
                });
              },
              child: Container(
                color: Colours.transparent,
                padding: const EdgeInsets.symmetric(horizontal: 16),
                child: Column(
                  children: <Widget>[
                    Row(
                      children: <Widget>[
                        Expanded(
                            child: Row(
                          children: <Widget>[
                            Container(
                                width: 24,
                                height: 24,
                                child: Image.asset(
                                    'images/${entity.imageName}.png')),
                            SizedBox(
                              width: 8,
                            ),
                            WidgetUtils.getTextColorView(entity.title,
                                Colours.text_2222, Dimens.FONT_SIZE_16),
                          ],
                        )),
                        Offstage(
                          offstage: entity.isUse ? false : true,
                          child: Icon(
                            entity.isCilke
                                ? Icons.radio_button_checked
                                : Icons.radio_button_unchecked,
                            color: entity.isCilke
                                ? Colours.themeColor
                                : Colours.gray_f0,
                            size: 24,
                          ),
                        ),
                      ],
                    ),
                    SizedBox(
                      height: 12,
                    ),
                    WidgetUtils.drawCodeDivider(),
                    // Offstage(
                    //   offstage: '1' == entity.id ? true : false,
                    //   child: _nbView(),
                    // ),
                  ],
                ),
              ),
            ); //赋值后的Widget
          }).toList(),
        );
      },
    );
  }

  Widget _nbView() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      children: <Widget>[
        WidgetUtils.itmeStyleView('品宣福利金',
            '剩余 ¥${this.widget.entity.valEntity.payCase.innerAcctPayFirst.fuliAcct.acctVal}',
            contentAlignment: Alignment.centerRight,
            textColor: Colours.gray_91,
            verticalPadding: 4,
            textSize: Dimens.FONT_SIZE_12,
            contentColor: Colours.gray_91),
        WidgetUtils.itmeStyleView('',
            '支付 ¥${this.widget.entity.valEntity.payCase.innerAcctPayFirst.fuliAcct.mustPay}',
            contentAlignment: Alignment.centerRight,
            textColor: Colours.gray_91,
            verticalPadding: 4,
            textSize: Dimens.FONT_SIZE_12,
            contentColor: Colours.themeColor),
        WidgetUtils.drawCodeDivider(),
        WidgetUtils.itmeStyleView('广告推广费',
            '剩余 ¥${this.widget.entity.valEntity.payCase.innerAcctPayFirst.tgfAcct.acctVal}',
            contentAlignment: Alignment.centerRight,
            textColor: Colours.gray_91,
            textSize: Dimens.FONT_SIZE_12,
            verticalPadding: 4,
            contentColor: Colours.gray_91),
        WidgetUtils.itmeStyleView('',
            '支付 ¥${this.widget.entity.valEntity.payCase.innerAcctPayFirst.tgfAcct.mustPay}',
            contentAlignment: Alignment.centerRight,
            textColor: Colours.gray_91,
            textSize: Dimens.FONT_SIZE_12,
            verticalPadding: 4,
            contentColor: Colours.themeColor),
        WidgetUtils.drawCodeDivider(),
        WidgetUtils.itmeStyleView('复购券',
            '剩余 ¥${this.widget.entity.valEntity.payCase.innerAcctPayFirst.reBuyAcct.acctVal}',
            contentAlignment: Alignment.centerRight,
            textColor: Colours.gray_91,
            textSize: Dimens.FONT_SIZE_12,
            verticalPadding: 4,
            contentColor: Colours.gray_91),
        WidgetUtils.itmeStyleView('',
            '支付 ¥${this.widget.entity.valEntity.payCase.innerAcctPayFirst.reBuyAcct.mustPay}',
            contentAlignment: Alignment.centerRight,
            textColor: Colours.gray_91,
            textSize: Dimens.FONT_SIZE_12,
            verticalPadding: 4,
            contentColor: Colours.themeColor),
        WidgetUtils.drawCodeDivider(),
        WidgetUtils.itmeStyleView('代理券',
            '剩余 ¥${this.widget.entity.valEntity.payCase.innerAcctPayFirst.dlqAcct.acctVal}',
            contentAlignment: Alignment.centerRight,
            textColor: Colours.gray_91,
            textSize: Dimens.FONT_SIZE_12,
            verticalPadding: 4,
            contentColor: Colours.gray_91),
        WidgetUtils.itmeStyleView('',
            '支付 ¥${this.widget.entity.valEntity.payCase.innerAcctPayFirst.dlqAcct.mustPay}',
            contentAlignment: Alignment.centerRight,
            textColor: Colours.gray_91,
            textSize: Dimens.FONT_SIZE_12,
            verticalPadding: 4,
            contentColor: Colours.themeColor),
        WidgetUtils.drawCodeDivider(),
        WidgetUtils.itmeStyleView('津贴',
            '剩余 ¥${this.widget.entity.valEntity.payCase.innerAcctPayFirst.jinTieAcct.acctVal}',
            contentAlignment: Alignment.centerRight,
            textColor: Colours.gray_91,
            textSize: Dimens.FONT_SIZE_12,
            verticalPadding: 4,
            contentColor: Colours.gray_91),
        WidgetUtils.itmeStyleView('',
            '支付 ¥${this.widget.entity.valEntity.payCase.innerAcctPayFirst.jinTieAcct.mustPay}',
            contentAlignment: Alignment.centerRight,
            textColor: Colours.gray_91,
            textSize: Dimens.FONT_SIZE_12,
            verticalPadding: 4,
            contentColor: Colours.themeColor),
        WidgetUtils.drawCodeDivider(),
        WidgetUtils.itmeStyleView('支付宝',
            '支付 ¥${this.widget.entity.valEntity.payCase.innerAcctPayFirst.zfbAcct.mustPay}',
            contentAlignment: Alignment.centerRight,
            textColor: Colours.gray_91,
            textSize: Dimens.FONT_SIZE_12,
            verticalPadding: 4,
            contentColor: Colours.themeColor),
      ],
    );
  }

  Widget _moneyView() {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 8),
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: Colours.title_white,
      ),
      child: WidgetUtils.getTextColorView(
          '¥ ${this.widget.entity.valEntity.payCase.shopPrice}',
          Colours.text_2222,
          Dimens.FONT_SIZE_30),
    );
  }

  // Widget _timeView() {
  //   return Container(
  //     padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
  //     alignment: Alignment.center,
  //     color: Colours.blackground_black_239,
  //     child: StreamBuilder(
  //       stream: _bloc.sendDate,
  //       initialData: _content,
  //       builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
  //         if (snapshot.data is String) {
  //           _content = snapshot.data;
  //         }
  //         return WidgetUtils.getTextColorView(
  //             '剩余时间$_content', Colours.yanqi_red, Dimens.FONT_SIZE_20);
  //       },
  //     ),
  //   );
  // }

  @override
  void dispose() {
    _bloc?.dispose();
    _zfbStartListSubscription?.cancel();
    _zfbCallblackListSubscription?.cancel();
    _zfbCompleteListSubscription?.cancel();
    _wxStartListSubscription?.cancel();
    super.dispose();
  }
}
